/**
 * @author Vanin Yuri
 * Date: 21.03.2009
 */
package univer.oko.olap;

import java.util.*;

public class MDXConstructor {
    private static MDXConstructor instance = new MDXConstructor();

    public static MDXConstructor getInstance() {
        return instance;
    }

    private MDXConstructor() {
    }

    private String MDXTemplate = "SELECT\n" +
            "{{^cols}} ON COLUMNS,\n" +
            "{^rows} ON ROWS\n" +
            "FROM [{^cube}]\n" +
            "WHERE ({^filter})";

    private Map<String, String> elements = new TreeMap<String, String>();

    public void addElement(String type, String element) {
        elements.put(element,type);
    }

    public void deleteElement(String element) {
        elements.remove(element);
    }

    public void clear() {
        elements.clear();
    }

    public boolean queryIsComplete() {
        boolean measure = false;
        boolean level = false;
        boolean filter = false;
        for(String type: elements.values())
            if (type.equals(OlapGenerator.GUI_FILTER))
                filter = true;
            else if (type.equals(OlapGenerator.GUI_MEASURE))
                measure = true;
            else if (type.equals(OlapGenerator.GUI_LEVEL))
                level = true;
        return measure && level && filter;
    }

    public String generateMDX(String cubeName) {
        String measure = "";
        String level = "";
        String filter = "";
        for(String element: elements.keySet())
            if (elements.get(element).equals(OlapGenerator.GUI_FILTER)) {
                if (!filter.equals(""))
                    filter += ", ";
                filter += element;
            }
            else if (elements.get(element).equals(OlapGenerator.GUI_MEASURE)) {
                if (!measure.equals(""))
                    measure += ", ";
                measure += "[Measures].[" + element + "]";
            }
            else if (elements.get(element).equals(OlapGenerator.GUI_LEVEL)) {
                if (level.equals(""))
                    level += "{" + element + ".Members" + "}";
                else {
                    level = level.replace("{","").replace("}","");
                    level = "Crossjoin(" + level + ", " + element + ".Members" + ")";
                }
            }
        return MDXTemplate.replace("{^cols}",measure).replace("{^rows}",level).
                           replace("{^cube}",cubeName).replace("{^filter}",filter);
    }
}
